﻿#if WINDOWS_UWP || NETFX_CORE
#region File and License Information

/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2012, Outcoder. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2013-03-21 20:07:26Z</CreationDate>
</File>
*/

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.UI.Notifications;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

using Outcoder.Services.DialogService;

namespace Outcoder.Services.Implementation
{
	public class DialogService : DialogServiceBase
	{
		public override async Task<DialogResult> ShowDialogAsync(
			object message, string caption, DialogButton dialogButton,
			DialogImage dialogImage = DialogImage.None,
			DialogImportance importanceThreshold = DialogImportance.High,
			object details = null,
			DialogController dialogController = null)
		{
			int? result;

			/* TODO: Make localizable resource. */
			switch (dialogButton)
			{
				case DialogButton.OK:

					result = await ShowDialogAsync(message, new List<object> { "OK" }, caption);
					if (result == 0)
					{
						return DialogResult.OK;
					}

					return DialogResult.None;

				case DialogButton.OKCancel:

					result = await ShowDialogAsync(message, new List<object> { "OK", "Cancel" }, caption);

					if (result == 0)
					{
						return DialogResult.OK;
					}
					else if (result == 1)
					{
						return DialogResult.Cancel;
					}

					return DialogResult.None;

				case DialogButton.YesNo:

					result = await ShowDialogAsync(message, new List<object> { "Yes", "No" }, caption);

					if (result == 0)
					{
						return DialogResult.Yes;
					}
					else if (result == 1)
					{
						return DialogResult.No;
					}

					return DialogResult.None;

				case DialogButton.YesNoCancel:
					result = await ShowDialogAsync(
								message, new List<object> { "Yes", "No", "Cancel" }, caption);

					if (result == 0)
					{
						return DialogResult.Yes;
					}
					else if (result == 1)
					{
						return DialogResult.No;
					}
					else if (result == 2)
					{
						return DialogResult.Cancel;
					}

					return DialogResult.None;

				default:
					throw new InvalidOperationException("Unknown DialogButton: " + dialogButton);
			}
		}

		public override async Task<int?> ShowDialogAsync(
			object question, IEnumerable<object> buttons, string caption = null,
			int defaultAcceptButton = -1, object details = null,
			DialogController dialogController = null)
		{
			string questionText = ArgumentValidator.AssertNotNull(question, "question").ToString();

			var messageDialog = new MessageDialog(questionText,
				caption ?? (DefaultMessageCaptionFunc != null ? DefaultMessageCaptionFunc() : string.Empty));

			var buttonList = buttons.ToList();
			int selectedIndex = -1;

			if (buttonList.Any())
			{
				for (int i = 0; i < buttonList.Count; i++)
				{
					int index = i;
					messageDialog.Commands.Add(new UICommand(buttonList[i].ToString(),
						cmd =>
						{
							selectedIndex = index;
						}));
				}
			}
			else
			{
				messageDialog.Commands.Add(new UICommand("OK"));
			}

			await messageDialog.ShowAsync();

			if (selectedIndex > -1)
			{
				return selectedIndex;
			}

			return null;
		}

		public async override Task<object> ShowToastAsync(ToastParameters toastParameters)
		{
			ArgumentValidator.AssertNotNull(toastParameters, "toastParameters");

			/* TODO: Implement image display. */

			var template = @"
<toast>
<visual>
<binding template=""ToastGeneric"">
  <text>{0}</text>
  <text>{1}</text>
</binding>
</visual>
</toast>
";
			var body = toastParameters.Body;

			var caption = toastParameters.Caption;
			var xml = string.Format(template, caption, body);
			var xmlDocument = new XmlDocument();
			xmlDocument.LoadXml(xml);
			var toast = new ToastNotification(xmlDocument);
			

			if (toastParameters.MillisecondsUntilHidden.HasValue)
			{
				toast.ExpirationTime = DateTimeOffset.Now.AddMilliseconds(
										toastParameters.MillisecondsUntilHidden.Value);
			}

			TaskCompletionSource<object> source = new TaskCompletionSource<object>();
			TypedEventHandler<ToastNotification, object> activatedHandler = null;
			TypedEventHandler<ToastNotification, ToastDismissedEventArgs> dismissedHandler = null;
			TypedEventHandler<ToastNotification, ToastFailedEventArgs> failedHandler = null;

			activatedHandler = (o, e) =>
			{
				toast.Activated -= activatedHandler;
				toast.Dismissed -= dismissedHandler;
				toast.Failed -= failedHandler;

				source.SetResult(e);
			};

			dismissedHandler = (o, e) =>
			{
				toast.Activated -= activatedHandler;
				toast.Dismissed -= dismissedHandler;
				toast.Failed -= failedHandler;

				source.SetResult(e.Reason);
			};

			failedHandler = (o, e) =>
			{
				toast.Activated -= activatedHandler;
				toast.Dismissed -= dismissedHandler;
				toast.Failed -= failedHandler;

				source.SetResult(e.ErrorCode);
			};

			toast.Activated += activatedHandler;
			toast.Dismissed += dismissedHandler;
			toast.Failed += failedHandler;

			ToastNotificationManager.CreateToastNotifier().Show(toast);

			return await source.Task;
		}

		public override Task<QuestionResponse<TResponse>> AskQuestionAsync<TResponse>(
			IQuestion<TResponse> question)
		{
			throw new NotImplementedException();
		}
	}
}
#endif